package com.hm.service.controller.chat;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.framework.request.post.PostBase;
import com.hm.service.framework.request.post.PostHandleBean;
import com.hm.service.framework.response.ResponseConstant;
import com.hm.service.framework.session.SessionUtils;
import com.hm.service.pojo.response.SessionResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.Instant;

@RestController
@RequestMapping(value = "/Chat", produces = {"application/json;charset=UTF-8"})
public class CFSS_000_000_000 extends PostBase {

    private static final Logger logger = LoggerFactory.getLogger(CFSS_000_000_000.class);

    //获取session接口
    @PostMapping(value = "/000_000_000")
    public String doPost(HttpServletRequest request) {
        return handleRequest(request);
    }

    @Override
    protected String postRequest(PostHandleBean requestBean) {
        String reqBody = requestBean.getReqBody();
        JSONObject jsonObject = (JSONObject) JSON.parse(reqBody);
        String timestamp = jsonObject.getString("timestamp");
        String signature = jsonObject.getString("signature");
        String userAgent = jsonObject.getString("userAgent");
        //校验签名
        if (signature == null || !signature.equals("#QWEdf^&589+")) {
            return errorResponse(ResponseConstant.PARAMETER_ERROR_CODE, "签名异常！", "");
        }
        //校验环境
//        if (userAgent == null || !userAgent.contains("micromessenger")) {
//            //不是微信环境
//            return errorResponse(ResponseConstant.PARAMETER_ERROR_CODE, "请在微信浏览器打开！", "");
//        }
        //计算时间戳差值不超过2分钟（与当前服务器时间对比）
        long l = calculateTimeDifference(Long.parseLong(timestamp), System.currentTimeMillis());
        long limit = 1000 * 60 * 2;
        if (l > limit) {
            //时间戳超时了
            return errorResponse(ResponseConstant.PARAMETER_ERROR_CODE, "timestamp超时！", "");
        }
        //时间戳和版本号建立对应关系，其他加密返回体需要用到
        SessionResponse response = new SessionResponse();
        response.sessionId = SessionUtils.generateId();
        return successResponse(requestBean.getRealSecretKey(), ResponseConstant.SUCCESS_CODE, "查询成功", response);
    }

    private static long calculateTimeDifference(long timestamp1, long timestamp2) {
        // 将时间戳转换为Instant对象
        Instant instant1 = Instant.ofEpochMilli(timestamp1);
        Instant instant2 = Instant.ofEpochMilli(timestamp2);
        // 计算时间差并返回结果（单位：毫秒）
        Duration duration = Duration.between(instant1, instant2);
        return duration.toMillis();
    }

}
